package com.swm.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.swm.mapper.StockDayDataMapper;
import com.swm.mapper.StockMapper;
import com.swm.pojo.Data;
import com.swm.pojo.Stock;
import com.swm.pojo.Stock_Day_Data;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 师文明
 * @data 2024/12/23 下午3:11
 **/
public class getStockDayData472 {


    public static DecimalFormat df = new DecimalFormat("#0.000");
    static SqlSession sqlSession = SqlSessionUtil.openSession();
    static StockMapper mapper = sqlSession.getMapper(StockMapper.class);
    static StockDayDataMapper stockDayDataMapper = sqlSession.getMapper(StockDayDataMapper.class);
    private static ArrayList<Data> dataList = new ArrayList<Data>();
    private static int allsize=0;
    private static int count=0;
    public static List<Stock> getStcokList() {
        List<Stock> stocks = mapper.selectAllStock();
        JSONObject jsonObject = new JSONObject();

        for (Stock stock : stocks) {
            String code = stock.getCode();
            int type = stock.getType();
            jsonObject.put(code, type);

        }
        return stocks;
    }

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        //获取所有股票列表
        List<Stock> stcokList = getStcokList();
        for (Stock stock : stcokList) {
            executorService.execute(() -> {
                try {
                    getData(stock);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }

        ///generateExcel(dataList);
        // executorService.shutdown();
    }

    public static void getData(Stock stock) throws Exception {

        String data = getWebData(stock.getCode(), stock.getType());
        if (data == null) {
            return;
        }

        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get("data") != null) {

            JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.get("data").toString());
            String name = jsonObject1.get("name").toString();
            JSONArray klines = JSONArray.parse(jsonObject1.get("klines").toString());
            //           开     收盘   最高 最低     成交额  成交量     振幅  涨跌幅  涨跌额  换手率  市盈率
            // 2025-03-21,75.60,71.77,76.22,71.77,36859,270881026.00,5.82,-6.17,-4.72,13.41
            int size = klines.size();

            System.out.println( allsize);
            System.out.println( count);
            if(size>500){
                size=500;
            }
            System.out.println(name + " :" + size);
            allsize+=size;
            count++;
            for(int i=0;i<size;i++){

                String s = klines.get(klines.size() - i-1).toString().split(",")[0];
                double v1 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[1]);
                double v2 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[2]);
                double v3 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[3]);
                double v4 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[4]);
                double v5 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[5]);
                double v6 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[6]);
                double v7 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[7]);
                double v8 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[8]);
                double v9 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[9]);
                double v10 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[10]);
                //double v11 = Double.parseDouble(klines.get(klines.size() - i-1).toString().split(",")[11]);

                Stock_Day_Data stockDayData = new Stock_Day_Data();
                stockDayData.setStock_id(stock.getId());
                stockDayData.setCode(stock.getCode());
                stockDayData.setName(stock.getName());
                stockDayData.setGetdate(s);
                stockDayData.setK(Double.valueOf(df.format(v1)));
                stockDayData.setS(Double.valueOf(df.format(v2)));
                stockDayData.setG(Double.valueOf(df.format(v3)));
                stockDayData.setD(Double.valueOf(df.format(v4)));
                stockDayData.setMoney(Double.valueOf(df.format(v5)));
                //double v = Double.valueOf(df.format(v6));
                //stockDayData.setMoneynum(v);
                stockDayData.setZf(Double.valueOf(df.format(v7)));
                stockDayData.setZdf(Double.valueOf(df.format(v8)));
                stockDayData.setZde(Double.valueOf(df.format(v9)));
                stockDayData.setHsl(Double.valueOf(df.format(v10)));
                stockDayDataMapper.insertStockDayData(stockDayData);
            }
            sqlSession.commit();

        }

    }

    public static String getWebData(String code, int type) {
        String data = null;
        try {
            //百度股票接口
            //String url = "https://finance.pae.baidu.com/vapi/v1/getquotation?group=quotation_kline_ab&code=" + code + "&ktype=day";
            // 连接到新浪财经接口
             String url = "https://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f116,f117&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&beg=0&end=20500101&rtntype=6&secid=" + type + "." + code + "&klt=101&fqt=1";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Cookie", "qgqp_b_id=488de58836c5f30c189b9ad4c700b9f5; st_si=04137509447995; websitepoptg_api_time=1734056942833; st_asi=delete; HAList=ty-1-603999-%u8BFB%u8005%u4F20%u5A92%2Cty-0-002888-%u60E0%u5A01%u79D1%u6280%2Cty-0-002269-%u7F8E%u90A6%u670D%u9970%2Cty-0-000813-%u5FB7%u5C55%u5065%u5EB7%2Cty-0-002045-%u56FD%u5149%u7535%u5668%2Cty-0-300059-%u4E1C%u65B9%u8D22%u5BCC%2Cty-1-688605-N%u5148%u950B%2Cty-1-000001-%u4E0A%u8BC1%u6307%u6570; st_pvi=62081555482493; st_sp=2024-12-11%2010%3A26%3A42; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=60; st_psi=20241213164756225-113200301201-5528754653");
            // 设置连接超时时间为 10 秒
            con.setConnectTimeout(10000);
            // 设置读取超时时间为 10 秒
            con.setReadTimeout(10000);
            // 从数据源获取实时股票数据
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            con.disconnect();
            data = response.toString();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            //e.printStackTrace();
        }
        return data;
    }
}

